import torch
import random
from .z_order import xyz2key as z_order_encode_
from .z_order import key2xyz as z_order_decode_
from .hilbert import encode as hilbert_encode_
from .hilbert import decode as hilbert_decode_
from .nps import encode as nps_encode_
from .nps import decode as nps_decode_
from .random import encode as random_encode_
from .random import decode as random_decode_

@torch.inference_mode()
def encode(grid_coord, batch=None, depth=16, order="z"):
    import time
    st = time.time()
    
    assert order in {"z", "z-trans", 
                     "hilbert", "hilbert-trans", 
                     "nps", "random",
                    }
    if order == "z":
        code = z_order_encode(grid_coord, depth=depth)
        print("z_order encode spend:", time.time()-st)
    elif order == "z-trans":
        code = z_order_encode(grid_coord[:, [1, 0, 2]], depth=depth)
    elif order == "hilbert":
        code = hilbert_encode(grid_coord, depth=depth)
        print("hilbert encode spend:", time.time()-st)
    elif order == "hilbert-trans":
        code = hilbert_encode(grid_coord[:, [1, 0, 2]], depth=depth)
    elif order == "nps":
        code = nps_encode(grid_coord, batch)
        print("nps encode spend:", time.time()-st)
    elif order == "random":
        code = random_encode(grid_coord, batch)
    else:
        raise NotImplementedError
    if batch is not None:
        batch = batch.long()
        code = batch << depth * 3 | code
    return code


@torch.inference_mode()
def decode(code, depth=16, order="z"):
    assert order in {"z", "hilbert", 
                    }
    batch = code >> depth * 3
    code = code & ((1 << depth * 3) - 1)
    if order == "z":
        grid_coord = z_order_decode(code, depth=depth)
    elif order == "hilbert":
        grid_coord = hilbert_decode(code, depth=depth) 
    else:
        raise NotImplementedError
    return grid_coord, batch


def z_order_encode(grid_coord: torch.Tensor, depth: int = 16):
    x, y, z = grid_coord[:, 0].long(), grid_coord[:, 1].long(), grid_coord[:, 2].long()
    # we block the support to batch, maintain batched code in Point class
    code = z_order_encode_(x, y, z, b=None, depth=depth)
    return code


def z_order_decode(code: torch.Tensor, depth):
    x, y, z = z_order_decode_(code, depth=depth)
    grid_coord = torch.stack([x, y, z], dim=-1)  # (N,  3)
    return grid_coord


def hilbert_encode(grid_coord: torch.Tensor, depth: int = 16):
    return hilbert_encode_(grid_coord, num_dims=3, num_bits=depth)


def hilbert_decode(code: torch.Tensor, depth: int = 16):
    return hilbert_decode_(code, num_dims=3, num_bits=depth)

def nps_encode(points: torch.Tensor, batch_indices: torch.Tensor):
    """
    编码器：输入点云与batch信息，输出一一对应的code
    参数:
    points: 输入点云 [N, 3]
    batch_indices: 每个点的batch编号 [N]，形状必须与points一致
    返回:
    codes: 编码结果 [N]，每个元素对应输入点的编码
    """
    return nps_encode_(points, batch_indices)

def nps_decode(codes: torch.Tensor, grid_coord: torch.Tensor = None):
    """
    解码器：从code中恢复batch、采样序号、原始索引，并根据grid_coord重建坐标
    参数:
    codes: 编码结果 [N]
    grid_coord: 网格坐标 [N, 3]，用于重建点云坐标（可选）
    """
    return nps_decode_(codes, grid_coord)

def random_encode(points: torch.Tensor, batch_indices: torch.Tensor):
    """
    编码器：输入点云与batch信息，输出一一对应的code
    参数:
    points: 输入点云 [N, 3]
    batch_indices: 每个点的batch编号 [N]，形状必须与points一致
    返回:
    codes: 编码结果 [N]，每个元素对应输入点的编码
    """
    return random_encode_(points, batch_indices)
def random_decode(codes: torch.Tensor, grid_coord: torch.Tensor = None):
    """
    解码器：从code中恢复batch、采样序号、原始索引，并根据grid_coord重建坐标
    参数:
    codes: 编码结果 [N]
    grid_coord: 网格坐标 [N, 3]，用于重建点云坐标（可选）
    """
    return random_decode_(codes, grid_coord)    



